

import java.util.Stack;

public class Solution {
     static class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;

        public TreeNode(int val) {
            this.val = val;
        }

    }
    public static TreeNode findmax(TreeNode root){
        if(root==null)return root;
        if(root.right==null)return root;
        else{
            return findmax(root.right);
        }
    }
    public static TreeNode findmin(TreeNode root){
        if(root==null)return root;
        if(root.left==null)return root;
        else{
            return findmin(root.left);
        }
    }

    public static  TreeNode Convert(TreeNode root) {
        if(root==null) return null;
        TreeNode node1 = findmax(root.left);
        TreeNode node2 = findmin(root.right);

        Convert(root.left);
        Convert(root.right);

        if(node1!=null){
            node1.right = root;
            root.left = node1;
        }
        if(node2!=null){
            root.right = node2;
            node2.left = root;
        }

        while(root.left!=null){
            root = root.left;
        }
        return root;
    }

    public static void inOrder(TreeNode root){
        TreeNode temp;
        Stack<TreeNode>  s= new Stack<>();
        s.add(root);
        while(!s.empty()) {
            temp = s.peek();
            while(temp.left!=null){
                s.add(temp.left);
                temp = temp.left;
            }
            while(!s.empty()){
                temp = s.pop();
                System.out.println(temp.val);
                if(temp.right != null){
                    s.add(temp.right);
                    break;
                }
            }
        }
    }
    public static void main(String args[]){
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        TreeNode node4 = new TreeNode(4);
        TreeNode node5 = new TreeNode(5);
        TreeNode node6 = new TreeNode(6);
        TreeNode node7 = new TreeNode(7);
        TreeNode node8 = new TreeNode(8);
        TreeNode node9 = new TreeNode(9);
        TreeNode node10 = new TreeNode(10);
        node1.left = node2;
        node1.right = node3;
        node2.left = node4;
        node2.right = node5;
        node3.left = node6;
        node3.right = node7;
        node4.left = node8;
        node4.right = node9;
        node5.left = node10;
//        node4.right = node9;
        TreeNode temp = Convert(node1);
        System.out.println("HAHA");
    }

}

